<template>
  <div id="app" class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <Alert v-bind:error="error" />
      </div>
    </div>
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <header>
          <h2 class="page-header">七叶<small> - 待办任务</small></h2>
        </header>
      </div>
    </div>
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <TodoInput v-on:on-add-todo="handleAddTodo" v-bind:hasError="error.has" />
      </div>
    </div>
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <TodoList
          v-bind:todos="todos"
          v-bind:total="total"
          v-bind:finished="finished"
          v-on:on-del-todo="handleDelTodo"
          v-on:on-change-todo="handleChangeTodo"
          v-on:on-save-todo="handleSaveTodo"
          v-on:on-clear-todo="handleClearTodo" />
      </div>
    </div>
  </div>
</template>

<script>
// 程序根组件，包含其他组件 - 不使用vuex的版本
import Alert from './Alert'
import TodoInput from './TodoInput'
import TodoList from './TodoList'

export default {
  name: 'app',
  components: {
    Alert,
    TodoInput,
    TodoList
  },
  data () {
    return {
      todos: [],
      error: {
        has: false,
        message: ''
      }
    }
  },
  computed: {
    total() {
      return this.todos.length;
    },
    finished() {
      let sum = 0
      this.todos.forEach((item, index) => {
        if (item.finished) sum = sum + 1
      })
      return sum
    }
  },
  created() {
    this._loadTodoFromStorage()
  },
  methods: {
    handleAddTodo(content) {
      if (!content) {
        this._setError(true, '请输入代办任务！')
        return;
      }
      this._initError();
      this.todos.unshift({
        content: content,
        finished: false
      });
    },
    handleDelTodo(index) {
      this.todos.splice(index, 1)
    },
    handleChangeTodo(index) {
      let todo = this.todos[index]
      todo.finished = !todo.finished
    },
    handleSaveTodo() {
      if (this.todos.length > 0) {
        localStorage.setItem('todos', JSON.stringify(this.todos))
      }
    },
    handleClearTodo() {
      let todos = localStorage.getItem('todos')
      if (todos) {
        localStorage.clear()
      }
    },
    _loadTodoFromStorage() {
      let todos = localStorage.getItem('todos')
      if (todos)
        this.todos = JSON.parse(todos)
    },
    _setError(has, message) {
      this.error.has = has;
      this.error.message = message;
    },
    _initError() {
      this.error.has = false;
      this.error.message = '';
    }
  }
}
</script>

<style>
  #app {
    margin: 20px auto;
  }
</style>
